package com.kaipizhe.controller;

import com.kaipizhe.model.LoginAuthDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/auth")
public class AuthController {

    public final JwtEncoder encoder;
    public AuthController(JwtEncoder encoder) {
        this.encoder = encoder;
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public String login(@RequestBody @Validated LoginAuthDTO data) {
        Instant now = Instant.now();
        long expiry = 36000L;

        JwtClaimsSet claims = JwtClaimsSet.builder()
                .issuer("self")
                .issuedAt(now)
                .expiresAt(now.plusSeconds(expiry))
                .subject(data.getAccount())
                .claim("uid", 1)
                .build();

        return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
    }

}
